package com.haierp.service.logistics.impl;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.haierp.util.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.haierp.exception.ErpCommonException;
import com.haierp.model.ErpOrder;
import com.haierp.model.ShippingOrder;
import com.haierp.service.IShippingOrderService;
import com.haierp.service.logistics.IOneCangService;
import com.haierp.util.HttpClientUtil;

import net.sf.json.JSONObject;
@Service("oneCangService")
public class OneCangServiceImpl implements IOneCangService {
	@Autowired
	private IShippingOrderService shippingOrderService;
	
	public static final String appid = "airuhua";
	public static final String appkey = "9e6t58gs5s2h4i1b";
	
	@Override
	public String createOrder(Long id) {
		ShippingOrder shippingOrder = shippingOrderService.selectById(id);
		if(shippingOrder == null) {
			throw new ErpCommonException("发货单号异常");
		}
		Map<String, Object> param = new HashMap<String, Object>();
		Map<String, Object> paramDataDetail = new HashMap<String, Object>();
		List<Map<String, Object>> goodsList = new ArrayList<>();
		List<ErpOrder> ErpOrderList = shippingOrderService.queryShippingOrderDetail(shippingOrder.getErpOrderId());
		String Timestamp = String.valueOf(getSecondTimestamp(new Date()));
		String token = toMD5(appkey+Timestamp);
		paramDataDetail.put("SelfOperate", false);
		paramDataDetail.put("WarehouseId", "1");
		paramDataDetail.put("ServiceCode", "US2CNTAX2");
		/*if(shippingOrder.getType() == 19) {
			paramDataDetail.put("ServiceCode", "US2CNTAX"); // 无忧专线代码：US2CNTAX(需要品牌,身份证), 无忧二线代码：US2CNTAX2
		} else {
			paramDataDetail.put("ServiceCode", "US2CNTAX2");
		}*/
		paramDataDetail.put("CustomerReference", shippingOrder.getShippingNo());
		paramDataDetail.put("Consignee", shippingOrder.getReceiver());
		paramDataDetail.put("Phone", shippingOrder.getTelephone());
		paramDataDetail.put("Province", shippingOrder.getReceiverState());
		paramDataDetail.put("City", shippingOrder.getReceiverCity());
		paramDataDetail.put("District", shippingOrder.getReceiverDistrict());
		paramDataDetail.put("Address", shippingOrder.getAddressDetail());
		paramDataDetail.put("IdentityCard", shippingOrder.getIdCard());
		
		ErpOrderList.forEach(erpOrder -> {
			Map<String, Object> goodparam = new HashMap<String, Object>();

			goodparam.put("OverseaTrackingNo", shippingOrder.getShippingNo());
			goodparam.put("SKU", erpOrder.getSkuCode());
			goodparam.put("CommodityName", erpOrder.getItemName());
			goodparam.put("UnitPrice", NumberUtil.formatDouble2(erpOrder.getSalePrice()*0.7));
			goodparam.put("ValueUnit", "CNY");
			goodparam.put("Brand", erpOrder.getBrand());
			goodparam.put("Quantity", erpOrder.getQuantity());
			goodsList.add(goodparam);
		});
		paramDataDetail.put("CommodityList", goodsList);
		param.put("timestamp", Timestamp);
		param.put("appid", appid);
		param.put("appkey", appkey);
		param.put("token", token);
		param.put("data", paramDataDetail);
		//JSONObject json = JSONObject.fromObject(param);
		//System.out.println(json);
		JSONObject jsonObject = HttpClientUtil.post("http://api.1hcang.com/Outbound/CreateOrder", null, param, "1");
		JSONObject shippingNoJson = JSONObject.fromObject(jsonObject);
	    if("1".equals(shippingNoJson.getString("code"))) {
	    	shippingOrder.setMistake(shippingNoJson.getString("msg"));
			shippingOrderService.updateSelectiveById(shippingOrder);
			return shippingNoJson.getString("msg");
	    } else {
			JSONObject dataJson = shippingNoJson.getJSONObject("data");
	    	shippingOrder.setLogisticNo(dataJson.getString("OutboundOrderNo"));
			shippingOrderService.updateSelectiveById(shippingOrder);
	    }
		
		return null;

	}
	

	
	public static void main(String[] args)  {  
	Map<String, Object> param = new HashMap<String, Object>();
	Map<String, Object> goodparam = new HashMap<String, Object>();
	Map<String, Object> paramDataDetail = new HashMap<String, Object>();
	List<Map<String, Object>> goodsList = new ArrayList<>();
	String Timestamp = String.valueOf(getSecondTimestamp(new Date()));

	//String appid = "airuhua";
	
	String testappid = "testapi";
	
	
	
	String tesappkey = "DC39AE3E28DC4FD3A3EB9331C4276C71";
	
	//String appkey = "9e6t58gs5s2h4i1b";
	
	String token = toMD5(tesappkey+Timestamp);

	
	paramDataDetail.put("SelfOperate", false);
	paramDataDetail.put("WarehouseId", "1");
	paramDataDetail.put("ServiceCode", "US2CNTAX2"); // 无忧专线代码：US2CNTAX(需要品牌), 无忧二线代码：US2CNTAX2
	paramDataDetail.put("CustomerReference", "PKG13215432674");
	paramDataDetail.put("Consignee", "王侃");
	paramDataDetail.put("Phone", "15088735320");
	paramDataDetail.put("Province", "浙江省");
	paramDataDetail.put("City", "杭州市");
	paramDataDetail.put("District", "西湖区");
	paramDataDetail.put("Address", "文三路东部软件园");
	paramDataDetail.put("IdentityCard", "310108199005251026");
	
	goodparam.put("OverseaTrackingNo", "65465478658");
	goodparam.put("SKU", "sku432543543");
	//goodparam.put("UPC", "sku432543543");
	goodparam.put("CommodityName", "雅诗兰黛精华");
	goodparam.put("UnitPrice", "26.89");
	goodparam.put("ValueUnit", "CNY");
	goodparam.put("Brand", "雅诗兰黛");
	goodparam.put("Quantity", 2);
	goodsList.add(goodparam);
	paramDataDetail.put("CommodityList", goodsList);
	
	param.put("timestamp", "");
	param.put("appid", testappid);
	param.put("appkey", tesappkey);
	param.put("token", token);
	param.put("data", paramDataDetail);
	JSONObject json = JSONObject.fromObject(param);
	System.out.println(json);
	JSONObject jsonObject = HttpClientUtil.post("http://testapi.1hcang.com/Outbound/CreateOrder", null, param, "1");
	System.out.println(jsonObject);
	JSONObject shippingNoJson = JSONObject.fromObject(jsonObject);
    if("1".equals(shippingNoJson.getString("code"))) {
		System.out.println(shippingNoJson.getString("msg"));
    } else {
		JSONObject dataJson = shippingNoJson.getJSONObject("data");
		System.out.println(dataJson.getString("OutboundOrderNo"));

    }
	
      }
	
	
	
	//精确到秒级别
	public static int getSecondTimestamp(Date date){  
	    if (null == date) {  
	        return 0;  
	    }  
	    String timestamp = String.valueOf(date.getTime());  
	    int length = timestamp.length();  
	    if (length > 3) {  
	        return Integer.valueOf(timestamp.substring(0,length-3));  
	    } else {  
	        return 0;  
	    }  
	} 
	
	
	private static String toMD5(String plainText) {
		String str = "";
		try {
			// 生成实现指定摘要算法的 MessageDigest 对象。
			MessageDigest md = MessageDigest.getInstance("MD5");
			// 使用指定的字节数组更新摘要。
			md.update(plainText.getBytes());
			// 通过执行诸如填充之类的最终操作完成哈希计算。
			byte b[] = md.digest();
			// 生成具体的md5密码到buf数组
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			str = buf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;

	}

}
